package com.bizdk.generator.core;

import com.bizdk.generator.common.exception.ServerException;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.StringReader;
import java.io.StringWriter;

/**
 * 模板工具类
 */
@Slf4j
public class TemplateUtils {
    
    /**
     * 获取模板渲染后的内容
     *
     * @param templateStr 模板内容
     * @param dataModel   数据模型
     */
    public static String getContent(final String templateStr, DataModel dataModel) {
        if (dataModel.isEmpty()) {
            return templateStr;
        }
        
        String content = "";
        try (StringReader reader = new StringReader(templateStr);
                StringWriter sw = new StringWriter();) {
            // 渲染模板
            String templateName = dataModel.get(DataModelConstant.TEMPLATE_NAME).toString();
            Template template = new Template(templateName, reader, null, "utf-8");
            template.process(dataModel, sw);
            
            content = sw.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServerException("渲染模板失败，请检查模板语法", e);
        }
        
        return content;
    }
}
